﻿@model verk2013_project_group12.Models.GameInstance

@section JavaScript
{
    <script src="@Url.Content("~/Scripts/jquery.signalR-1.0.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/signalr/hubs")" type="text/javascript"></script>
}

<p id="waiting"><strong>Waiting for a player</strong></p>

@{Html.RenderPartial("_Chat");}

<table id="ticTacToe">
    <tr class="ticTacToeRow">
        <td class="ticTacToeButton" id="cell1"></td>
        <td class="ticTacToeButton" id="cell2"></td>
        <td class="ticTacToeButton" id="cell3"></td>
    </tr>

    <tr class="ticTacToeRow">
        <td class="ticTacToeButton" id="cell4"></td>
        <td class="ticTacToeButton" id="cell5"></td>
        <td class="ticTacToeButton" id="cell6"></td>
    </tr>

    <tr class="ticTacToeRow">
        <td class="ticTacToeButton" id="cell7"></td>
        <td class="ticTacToeButton" id="cell8"></td>
        <td class="ticTacToeButton" id="cell9"></td>
    </tr>
</table>

<p id="turn"></p>

<script>
    $(document).ready(function () {
        $("#ticTacToe").hide();
        $(".playerList").hide();
        $(".leaderboard").hide();
        $("#menu").hide();

        $(function () {
            var group = '@(Model.ID)';
        var hub = $.connection.gameHub;

        var squares = $(".ticTacToeButton");
        var over = false;
        var win = false;
        var yourTurn = true;
        
        // This function returns true if there is a win
        function checkForWin(squares, symbol) {
            if (document.all) {
                if (squares[0].innerText == symbol &&
               squares[1].innerText == symbol &&
               squares[2].innerText == symbol) {
                    hub.server.winningIds(squares[0].id, squares[1].id, squares[2].id);
                    return true;
                }

                if (squares[3].innerText == symbol &&
                   squares[4].innerText == symbol &&
                   squares[5].innerText == symbol) {
                    hub.server.winningIds(squares[3].id, squares[4].id, squares[5].id);
                    return true;
                }

                if (squares[6].innerText == symbol &&
                   squares[7].innerText == symbol &&
                   squares[8].innerText == symbol) {
                    hub.server.winningIds(squares[6].id, squares[7].id, squares[8].id);
                    return true;
                }

                if (squares[0].innerText == symbol &&
                   squares[3].innerText == symbol &&
                   squares[6].innerText == symbol) {
                    hub.server.winningIds(squares[0].id, squares[3].id, squares[6].id);
                    return true;
                }

                if (squares[1].innerText == symbol &&
                   squares[4].innerText == symbol &&
                   squares[7].innerText == symbol) {
                    hub.server.winningIds(squares[1].id, squares[4].id, squares[7].id);
                    return true;
                }

                if (squares[2].innerText == symbol &&
                   squares[5].innerText == symbol &&
                   squares[8].innerText == symbol) {
                    hub.server.winningIds(squares[2].id, squares[5].id, squares[8].id);
                    return true;
                }

                if (squares[0].innerText == symbol &&
                   squares[4].innerText == symbol &&
                   squares[8].innerText == symbol) {
                    hub.server.winningIds(squares[0].id, squares[4].id, squares[8].id);
                    return true;
                }

                if (squares[2].innerText == symbol &&
                   squares[4].innerText == symbol &&
                   squares[6].innerText == symbol) {
                    hub.server.winningIds(squares[2].id, squares[4].id, squares[6].id);
                    return true;
                }
            }
            else {
                // For mozilla
                if (squares[0].textContent == symbol &&
                    squares[1].textContent == symbol &&
                    squares[2].textContent == symbol) {
                    hub.server.winningIds(squares[0].id, squares[1].id, squares[2].id);
                    return true;
                }

                if (squares[3].textContent == symbol &&
                    squares[4].textContent == symbol &&
                    squares[5].textContent == symbol) {
                    hub.server.winningIds(squares[3].id, squares[4].id, squares[5].id);
                    return true;
                }

                if (squares[6].textContent == symbol &&
                    squares[7].textContent == symbol &&
                    squares[8].textContent == symbol) {
                    hub.server.winningIds(squares[6].id, squares[7].id, squares[8].id);
                    return true;
                }

                if (squares[0].textContent == symbol &&
                    squares[3].textContent == symbol &&
                    squares[6].textContent == symbol) {
                    hub.server.winningIds(squares[0].id, squares[3].id, squares[6].id);
                    return true;
                }

                if (squares[1].textContent == symbol &&
                    squares[4].textContent == symbol &&
                    squares[7].textContent == symbol) {
                    hub.server.winningIds(squares[1].id, squares[4].id, squares[7].id);
                    return true;
                }

                if (squares[2].textContent == symbol &&
                    squares[5].textContent == symbol &&
                    squares[8].textContent == symbol) {
                    hub.server.winningIds(squares[2].id, squares[5].id, squares[8].id);
                    return true;
                }

                if (squares[0].textContent == symbol &&
                    squares[4].textContent == symbol &&
                    squares[8].textContent == symbol) {
                    hub.server.winningIds(squares[0].id, squares[4].id, squares[8].id);
                    return true;
                }

                if (squares[2].textContent == symbol &&
                    squares[4].textContent == symbol &&
                    squares[6].textContent == symbol) {
                    hub.server.winningIds(squares[2].id, squares[4].id, squares[6].id);
                    return true;
                }
            }
        }

        // This function returns true if all the cells have been filled
        function checkForEnd(squares) {
            for (var i = 0; i < squares.length; i++) {
                if (document.all) {
                    if (squares[i].innerText.length == 0) {
                        return false;
                    }
                }
                else {
                    // For mozilla
                    if (squares[i].textContent.length == 0) {
                        return false;
                    }
                }
            }
            return true;
        }
        
        // At the start of the game, let the players know whos turn it is
        hub.client.initPlayerTurn = function (playerId) {
            if (playerId == 1) {
                yourTurn = true;
                $("#turn").html("<strong>Your turn!</strong>");
            }
            else {
                yourTurn = false;
                $("#turn").html("<strong>Waiting for the other player to move</strong>");
            }
        }
        
        // This function is called after the opponent makes a move
        hub.client.cellClicked = function (cellId) {
            /* For some strange reason the jquery function doesn't seem to work for particular selectors 
             inside this function, which is the reason why appropriate functions and variables are not being used
             (for example re-selecting the cells).
            */
            var theCell = $("#" + cellId);
            if (theCell.text() == "" && !over && !win) {
                theCell.text("O");
                yourTurn = true;
                $("#turn").html("<strong>Your turn!</strong>");
                if (!win) {
                    win = checkForWin(squares, 'O');
                }
                over = true; // Assume there is a draw
                if (!win) {
                    // Check if there's actually a draw
                    var cells = [];
                    for (var i = 0; i < 9; i++) {
                        cells[i] = $("#cell" + (i + 1));
                    }
                    for (var i = 0; i < cells.length; i++) {
                        if (cells[i].text().length == 0) {
                            over = false;
                            break;
                        }
                    }
                }
            }
            if (over || win) {
                // If the game is over
                if (win) {
                    // If someone won
                    $("#turn").html("<strong>Sorry, you lost the game.</strong>");
                }
                else {
                    // If there is a draw
                    $("#turn").html("<strong>It's a draw</strong>");
                }
            }
        };

        hub.client.showCells = function (username) {
            $("#ticTacToe").show();
            $("#waiting").html("<strong>You are playing against " + username + "</strong>");
        };

        hub.client.showWinningCells = function (id1, id2, id3) {
            $("#" + id1).addClass("winningCell");
            $("#" + id2).addClass("winningCell");
            $("#" + id3).addClass("winningCell");
        };

        hub.client.concede = function () {
            win = true;
            $("#turn").html("<strong>Congratulations, you won the game! Additional points have been added to your account.</strong>");
            alert("You won! Your opponent has conceded!")
        }

        hub.client.eraseCells = function () {
            $("#waiting").html("<strong>This game is already in progress, please find another game in the lobby</strong>");
        };

        hub.client.broadcastMessage = function (username, message) {
            // Broadcast chat messages to the players
            var encodedName = $("<div />").text(username).html();
            var encodedMsg = $("<div />").text(message).html();
            $("#discussion").prepend('<li><strong>' + encodedName
                + '<strong>: &nbsp; &nbsp;' + encodedMsg + '</li>');
        };

        $("#message").focus();

        $.connection.hub.start().done(function () {
            hub.server.join(group);

            $(".ticTacToeButton").click(function () {
                if (yourTurn && !over && !win) {
                    hub.server.clickCell(group, this.id);
                    if ($(this).text() == "") {
                        $(this).text("X");
                        yourTurn = false;
                        $("#turn").html("<strong>Waiting for the other player to move</strong>");
                        over = checkForEnd(squares);
                        if (!win) {
                            win = checkForWin(squares, "X");
                        }
                    }
                    if (over || win) {
                        if (win) {
                            alert("Congratulations, you won the game!");
                            hub.server.ticTacToeWin(group);
                            $("#turn").html("<strong>Congratulations, you won the game! Additional points have been added to your account.</strong>");
                        }
                        else {
                            $("#turn").html("<strong>It's a draw</strong>");
                        }
                    }
                }
            });

            window.onbeforeunload = function () {
                if (!over && !win) {
                    hub.server.ticTacToeQuit(group);
                }
                else {
                    hub.server.ticTacToeEnd(group);
                }
            };

            $(window).unload(function () {
                if ($.browser.opera) {
                    if (!over && !win) {
                        hub.server.ticTacToeQuit(group);
                    }
                    else {
                        hub.server.ticTacToeEnd(group);
                    }
                }

            });

            $(document.body).delegate('#message', 'keypress', function (e) {
                // Enables the players to use 'enter' to send messages
                if (e.which === 13) { // if is enter
                    hub.server.send(group, $("#message").val());
                    $("#message").val("").focus();
                }
            });

            $("#sendmessage").click(function () {
                hub.server.send(group, $("#message").val());
                $("#message").val("").focus();
            });
        });
    });
});
</script>